package ruc.InfluxDB.write;

import okhttp3.*;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.InfluxDB.InfluxDB_Common;

import java.io.IOException;


public class InfluxDB_MultiTableWrite {
    private String writeURL = "";
    private String tbName = "";

    MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");

    public InfluxDB_MultiTableWrite(String IP, String port, String tbName, String dbName) {
        String baseUrl = String.format("http://%s:%s", IP, port);
        this.writeURL = baseUrl + "/write?precision=ms&db=" + dbName;
        this.tbName = tbName;
    }

    private void MultiTableWrite(String[] values, int[] tableNum) throws IOException {
        int idx = 0;
        long[] cnt = new long[tableNum.length];
        while(idx < values.length) {
            for(int i = 0; i < tableNum.length; i++) {
                StringBuilder sb = new StringBuilder();
                for(int j = 0; j < tableNum[i]; j++) {
                    if (idx == values.length) {
                        System.out.printf("[TSBench-D] >>>>>>>> index out of bounds, the length of array:%d >>>>>>>>>>>> \n", values.length);
                        break;
                    }

                    String[] v = values[idx++].split(constant.Delimiter);
                    // table not exists is to create
                    String eSQL = String.format("%s,userInfo=%s,server=%s,hostname=%s cpu_usage=%s,disk_usage=%s,memory_usage=%s %s", tbName+j, v[1], v[2], v[3], v[4], v[5], v[6], v[0]);
                    sb.append(eSQL);
                }
                //batch insert
                Request request = new Request.Builder()
                        .url(writeURL)
                        .post(RequestBody.create(MEDIA_TYPE_TEXT, sb.toString()))
                        .build();

                long costTime = InfluxDB_Common.sendRequest(request);
                cnt[i] += costTime;
            }
        }

        for(int i = 0; i < cnt.length; i++) {
            System.out.printf("[TSBenchD] [InfluxDB_MultiTableWrite] >>>>> tableNum：%d, costTime：%d >>>>> \n", tableNum[i], cnt[i]);
            IOUtils.WriteData(constant.GetWriteFilePath("InfluxDB", "MultiTableWrite"),
                    new String[]{String.valueOf(tableNum[i]), String.valueOf(cnt[i])});
        }
    }

    public static void main(String[] args) throws IOException {
        InfluxDB_MultiTableWrite db = new InfluxDB_MultiTableWrite(constant.IP, constant.InfluxDB_Port, constant.MultiTableWrite_tbName,constant.dbName);
        db.MultiTableWrite(IOUtils.GetData(), constant.MutiTable_TableNum);
    }
}
